using System;
using System.IO;
using System.Web;
using ECatalog.Models.Helpers;

namespace ECatalog.Models.Models
{
    public class ModelBuilder : IModelBuilder
    {
        private readonly IModelRepository modelRepository;

        private static string StorageRoot
        {
            get { return Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Files/")); } //Path should! always end with '/'
        }

        public ModelBuilder(IModelRepository modelRepository)
        {
            this.modelRepository = modelRepository;
        }

        public Model Build(ModelView modelView)
        {
            var m = new Model
                {
                    Description = modelView.Description,
                    ModelId = modelView.ModelId,
                    CatNumber = modelView.CatNumber,
                    Price = modelView.Price,
                    Sale = modelView.Sale,
                    SalePrice = modelView.SalePrice,
                    OrganizationId = modelView.OrganizationId,
                    ImageUrl = modelView.ImageUrl,
                    TypeImage = modelView.TypeImage
                };

            return m;
        }

        public void Save(Model model)
        {
            modelRepository.SaveModel(model);
        }

        public ModelView BuildVm(int id)
        {
            return modelRepository.GetViewModel(id);
        }

        public void SaveFile(HttpPostedFileBase uploadedFile, Model model)
        {
            if (uploadedFile.ContentType.Equals("image/jpeg") || uploadedFile.ContentType.Equals("image/png") || uploadedFile.ContentType.Equals("image/gif"))
            {
                var file = uploadedFile;
                var fileName = String.Format("{0}-{1}", Guid.NewGuid(), file.FileName.ToLower());
                var trimName = fileName.Remove(fileName.LastIndexOf('.'));

                var path = Path.Combine(StorageRoot, "Organization-" + model.OrganizationId.ToString(), "Model-" + model.ModelId.ToString(), trimName);
                var path320 = Path.Combine(path, "320x240\\");
                var path800 = Path.Combine(path, "800x600\\");
                ImageHelper.CreateDirectory(path);
                ImageHelper.CreateDirectory(path320);
                ImageHelper.CreateDirectory(path800);

                if (Directory.Exists(path) && Directory.Exists(path320) && Directory.Exists(path800))
                {
                    ImageHelper.BuildImage(file, path320, fileName, 320, 240);
                    ImageHelper.BuildImage(file, path800, fileName, 800, 600);
                }

                model.ImageUrl = trimName;
                model.TypeImage = ImageHelper.GetImageType(uploadedFile.ContentType);
                modelRepository.SaveModel(model);
            }
        }
    }
}